

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TreeView extends JTree implements Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 203807913022323892L;
	private Document doc = null;

	public TreeView(RemoteObserverInterface obs) {

		((RemoteObserver)obs).Attach(this);

		this.doc = ((RemoteObserver)obs).getDoc();
		setSize(150, 600);
		System.out.println("Creating treeview");
		System.out.println("With docname: "+this.doc.name);

		DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
		
		setModel(new DefaultTreeModel(root));

	}


	@Override
	public void Update(Subject sub) {
		this.doc = sub.getDoc();
		System.out.println("Updating view: "+this.doc.name);

		setModel(new DefaultTreeModel(genTree(this.doc.getRootobj())));
	}

	private DefaultMutableTreeNode genTree(GlobalObject obj) {

		DefaultMutableTreeNode tmp = null;

		if (obj instanceof ObjectGroup) {
			tmp = new DefaultMutableTreeNode("group");
			System.out.println("Creating node");
			for (GlobalObject ob : ((ObjectGroup) obj).children) {
				tmp.add(genTree(ob));
			}
		} else {
			tmp = new DefaultMutableTreeNode(obj.getClass().getSimpleName());
			System.out.println("Creating leaf "+obj.getClass().getSimpleName());
		}
		return tmp;
	}

}
